<template>
  <view class="animated fadeIn faster m-2" style="min-height: 100vh;">
    <view class="searchBox px-2 rounded20 d-flex-item d-flex d-flex-middle bg-fff">
      <input  v-model="formData.name" class="pl-1 rounded10 font30 d-flex-item" placeholder="搜索课程"
              placeholder-class="colorhold"/>
      <text v-if="formData.name" class="text-right iconfont icon-cuo1 main-color ml-1"
            @click="dataCancel"></text>
      <text class="iconfont icon-icon_sousuo main-color font40  text" @click="onSearch"></text>
    </view>

    <!-- 课程列表 -->
    <view class="course-list mt-3">
      <view
          v-for="(course, index) in courseList"
          :key="index"
          class="course-item-wrapper mb-2"
          @touchstart="onTouchStart($event, index)"
          @touchend="onTouchEnd($event, index)"
      >
        <view
            class="course-item bg-fff rounded10 p-2"
        >
          <view class="d-flex">
            <!-- 左侧课程封面 -->
            <view class="course-cover mr-2">
              <image
                  :src="course.course_image"
                  mode="aspectFill" style="width: 200rpx; height: 150rpx; border-radius: 10rpx;"
              ></image>
            </view>

            <!-- 右侧课程信息 -->
            <view class="course-info d-flex-item">
              <view class="course-title font30 font-bold mb-1">{{ course.course_name }}</view>
              <view class="course-8e8e8e color-92 font24 mb-1">
                <text>{{ course.course_id }} 课时</text>
                <text class="ml-3">已收藏</text>
<!--                <text class="ml-3">已听 {{ course.view_duration_text }}</text>-->
              </view>
              <view class="d-flex d-flex-between d-flex-middle">
                <view class="course-8e8e8e color-92 font24">
                  <text>{{ course.favorite_time }}</text>
                </view>
                <view>
                  <view
                      class="study-btn font20"
                      :class="course.status === '已完成' ? 'completed-btn' : 'continue-btn'"
                      @click="goUrl(`/subPages/courseDetails/courseDetails?id=${course.course_id}`)"
                  >
                    {{ course.status === '已完成' ? '重新学习' : '去学习' }}
                  </view>
                </view>
              </view>
            </view>

            <!-- 取消收藏按钮 -->
            <view
                class="cancel-btn font20 colorfff font26"
                :class="{'show': course.showCancelBtn}"
                @click="cancelCollection(index)"
            >
              取消收藏
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>


<script>
import {fileApi} from '@/http/fileApi.js';
import {homeApi} from "@/http/homeApi";
import {mapState} from "vuex"

export default {
  data() {
    return {
      formData: {
        name: ''
      },
      activeSwipeIndex: -1,
      courseList: [
      ]
    }
  },
  onLoad() {
    this.goMyCoursesList()
  },
  methods: {
    async goMyCoursesList() {
      let res = await fileApi.favoriteCourses({
        keyword: this.formData.name
      })
      this.courseList = res.courses
    },
    // 触摸开始
    onTouchStart(e, index) {
      const touch = e.touches[0];
      this.$set(this.courseList[index], 'touchStartX', touch.clientX);
      this.$set(this.courseList[index], 'touchStartTime', Date.now());
    },

    // 触摸结束
    onTouchEnd(e, index) {
      const course = this.courseList[index];
      const touch = e.changedTouches[0];
      const deltaX = course.touchStartX - touch.clientX;
      const deltaTime = Date.now() - course.touchStartTime;

      // 判断是否为左滑手势（滑动距离>50px且时间<500ms）
      if (deltaX > 50 && deltaTime < 500) {
        // 隐藏之前显示的按钮
        if (this.activeSwipeIndex !== -1 && this.activeSwipeIndex !== index) {
          this.$set(this.courseList[this.activeSwipeIndex], 'showCancelBtn', false);
        }
        // 显示当前按钮
        this.$set(this.courseList[index], 'showCancelBtn', true);
        this.activeSwipeIndex = index;
      } else if (deltaX < -30) {
        // 右滑隐藏
        this.$set(this.courseList[index], 'showCancelBtn', false);
        if (this.activeSwipeIndex === index) {
          this.activeSwipeIndex = -1;
        }
      }
    },
    // 取消收藏
    async cancelCollection(index) {
      uni.showModal({
        title: '确认取消收藏',
        content: '确定要取消收藏该课程吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const courseId = this.courseList[index].course_id;
              // 从列表中移除课程
              this.courseList.splice(index, 1);
              this.activeSwipeIndex = -1; // 重置活动索引
              await homeApi.removeFavorite({ course_id: courseId });
              uni.showToast({
                title: '已取消收藏',
                icon: 'success'
              });
            } catch (error) {
              uni.showToast({
                title: '取消收藏失败',
                icon: 'none'
              });
            }
          } else {
            // 隐藏取消按钮
            this.$set(this.courseList[index], 'showCancelBtn', false);
            this.activeSwipeIndex = -1; // 重置活动索引
          }
        }
      });
    },
    goUrl(urlPages, data) {
      if (!this.loginState) {
        uni.showToast({
          title: '未登录，请先登录！',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({
            url: '/subPages/login/login'
          })
        }, 1500)
      } else {
        uni.navigateTo({
          url: urlPages
        })
      }
    },
    onSearch() {
      this.goMyCoursesList();
    },
    dataCancel() {
      this.formData.name = '';
      this.goMyCoursesList(); // 重新加载课程列表
    },
  }
}
</script>

<style scoped>
.searchBox {
  background-color: #fff;
  height: 80rpx;
  line-height: 80rpx;
}

.searchBox input {
  height: 100%;
}

.study-btn {
  padding: 10rpx 20rpx;
  border-radius: 30rpx;
  height: auto;
  line-height: 1;
}

.continue-btn {
  color: #3E8EFF;
  border: 1rpx solid #3E8EFF;
}

.completed-btn {
  color: #666;
  border: 1rpx solid #ddd;
}

.course-item-wrapper {
  overflow: hidden;
  border-radius: 10rpx;
  position: relative;
}

.cancel-btn {
  background: rgba(212, 48, 48, 1);
  position: absolute;
  width: 140rpx;
  height: 100%;
  top: 0;
  right: -140rpx; /* 初始位置在右侧外部，完全隐藏 */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: right 0.3s ease; /* 添加滑入动画 */
}

.cancel-btn.show {
  right: 0; /* 显示时滑入到正确位置 */
}

.course-8e8e8e {
  color: #8e8e8e;
}
</style>
